package com.base.test.rabbitmq.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.base.test.rabbitmq.dto.MqQueueReq;
import com.base.test.rabbitmq.properties.Rabbit1Properties;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@EnableConfigurationProperties(Rabbit1Properties.class)
public class MqQueueServieImpl implements MqQueueService{

    @Autowired
    private Rabbit1Properties rabbit1Properties;

    @Override
    public Map getQueueMessages(MqQueueReq mqQueueReq){
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        Map<String, List<? extends Object>> result = new HashMap<>();
        try {
            String uri = "/api/queues/%2f"+mqQueueReq.getVhost()+"/"+mqQueueReq.getQueuename()+"/get";
            HttpHost host = new HttpHost(rabbit1Properties.getHost(), 15672);
            //入参
            Map<String,Object> paramMap = new HashMap<>();
            paramMap.put("count",mqQueueReq.getCount());
            paramMap.put("ackmode",mqQueueReq.getAckmode());
            paramMap.put("encoding","auto");
            paramMap.put("truncate",mqQueueReq.getTruncate());
            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(new StringEntity(JSONObject.toJSONString(paramMap),
                    ContentType.create("application/json", "utf-8")));
            httpPost.setHeader("Content-Type", "application/json");
            //认证
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(rabbit1Properties.getHost(),15672),
                    new UsernamePasswordCredentials(rabbit1Properties.getUsername(),rabbit1Properties.getPassword()));
            client = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
            response = client.execute(host,httpPost);
            HttpEntity entity = response.getEntity();
            if(null!= entity){
                String jsonEntityStr = EntityUtils.toString(entity);
                JSONArray jsonArray = JSONArray.parseArray(jsonEntityStr);
                List<JSONObject> payloads = new LinkedList<>();
                List<String> productBarcodes = new LinkedList<>();
                for (Object obj:jsonArray) {
                    Map objMap = (Map)obj;
                    String payload = (String) objMap.get("payload");
                    JSONObject jsonObject = JSONObject.parseObject(payload);
                    payloads.add(jsonObject);
                    String jsonList = jsonObject.getString("list");
                    JSONArray jsons = JSONArray.parseArray(jsonList);
                    for (Object msg:jsons) {
                        Map msgMap = (Map) msg;
                        String productBarcode = (String) msgMap.get("product_barcode");
                        productBarcodes.add(productBarcode);
                    }
                }
                result.put("msg_list",payloads);
                result.put("product_barcode_list",productBarcodes);
            }
        }catch (Exception e){
            log.error("获取虚拟主机:{}队列:{}消息失败:{}",mqQueueReq.getVhost(),mqQueueReq.getQueuename(),e);
        }finally {
            try {
                if(null!=response){
                    response.close();
                }
                if(null!=client){
                    client.close();
                }
            }catch(IOException e){
                log.error("关闭HTTP响应及连接失败");
            }
        }
        return result;
    }
}
